package com.yict.csms.system.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yict.common.entity.PageEntity;
import com.yict.common.service.impl.CommonService;
import com.yict.common.util.CipherUtil;
import com.yict.csms.company.entity.Company;
import com.yict.csms.system.dao.impl.UserDaoImpl;
import com.yict.csms.system.dao.impl.UserDataperDaoImpl;
import com.yict.csms.system.dao.impl.UserUserGroupDaoImpl;
import com.yict.csms.system.entity.BudgetNum;
import com.yict.csms.system.entity.Dataper;
import com.yict.csms.system.entity.User;
import com.yict.csms.system.entity.UserDataper;
import com.yict.csms.system.entity.UserGroup;
import com.yict.csms.system.entity.UserUserGroup;
import com.yict.csms.system.service.IUserService;

/**
 * 
 * 
 * @author Patrick.Deng
 * 
 */
@Service
public class UserServiceImpl extends CommonService<User, Long> implements
		IUserService {
	@Autowired
	private UserDaoImpl userDaoImpl;

	@Autowired
	private UserUserGroupDaoImpl userUserGroupDaoImpl;
	
	@Autowired
	private UserDataperDaoImpl userDataperDaoImpl;

	public List<User> search(Map<String, Object> queryMap, PageEntity page) {
		StringBuilder queryString = new StringBuilder();
		String field = " order by c.createDate desc";
		pageEntity = new PageEntity();
		queryString.append("from User as c where 1=1 and c.userStutas <> 'delete' ");
		// queryString.append(" where 1=1 and c.userStutas <> 'delete'");
		if (queryMap != null && queryMap.size() > 0) {
			if (queryMap.get("companyIdList") != null && !"".equals(queryMap.get("companyIdList"))) {
				queryString.append(" and c.company.companyId in(:companyIdList)");
			}
			if (queryMap.get("companyName") != null && !"".equals(queryMap.get("companyName"))) {
				queryString.append(" and lower(c.company.companyName) like :companyName");
				queryMap.put("companyName", queryMap.get("companyName").toString().toLowerCase());
			}
			if (queryMap.get("department") != null && !"".equals(queryMap.get("department"))) {
				queryString.append(" and lower(c.department) like :department");
				queryMap.put("department", queryMap.get("department").toString().toLowerCase());
			}
			if (queryMap.get("userGroupId") != null && !"".equals(queryMap.get("userGroupId"))) {
				queryString
						.append(" and c.userId in(select u.user.userId from UserUserGroup u where u.userGroup.userGroupId = :userGroupId)");
			}
			if (queryMap.get("userName") != null && !"".equals(queryMap.get("userName"))) {
				queryString.append(" and lower(c.userName) like :userName");
				queryMap.put("userName", queryMap.get("userName").toString().toLowerCase());
			}
		}
		if (page.getField() != null && !"".equals(page.getField()) && page.getOrder() != null
				&& !"".equals(page.getOrder())) {
			if (page.getField().equals("companySName")) {
				field = " order by c.company." + page.getField() + page.getOrder();
			} else if (page.getField().equals("companyName")) {
				field = " order by c.company." + page.getField() + page.getOrder();
			} else if (page.getField().equals("userGroupNm")) {
				field = " left join fetch c.userUserGroup b"/* + page.getOrder() */;
				// field = " ,UserUserGroup b and b.user.userId = c.userId order by b.userGroup.userGroupName " +
				// page.getOrder();
			} else {
				field = " order by c." + page.getField() + page.getOrder();
			}
		}
		queryString.append(field);

		List<User> list = userDaoImpl.search(queryString.toString(), queryMap, page);
		pageEntity.setTotalRecord(userDaoImpl.getPageEntity().getTotalRecord());
		return list;
	}
	
	/**
	 * 根据id查找实体
	 * @param ids
	 * @return
	 */
	public List<User> listByIds(Collection<Long> ids){
		if(ids == null || ids.size() == 0) return new ArrayList<User>();
		String hql = "from User t where userId in (:ids)";
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("ids", ids);
		List<User> list;
		try {
			list = userDaoImpl.search(hql,map, null);
		} catch (Exception e) {
			list = new ArrayList<User>();
		}
		return list;
	}

	public List<UserUserGroup> findGroupByUserId(String ids) {
		String queryString = "from UserUserGroup u where u.user.userId in("
				+ ids + ") order by u.user.createDate";
		return userUserGroupDaoImpl.find(queryString);
	}
	
	public List<UserDataper> findDataperByUserId(String ids) {
		String queryString = "from UserDataper u where u.user.userId in("
			+ ids + ") order by u.user.createDate";
		return userDataperDaoImpl.find(queryString);
	}

	@Override
	public User findById(Long id) {
		return userDaoImpl.findbyId(id);
	}

	@Transactional(readOnly = false)
	public boolean save(User user, HashMap<Long, String> userGroupFlag, HashMap<Long, String> userDataperIdFlag) {
		boolean bool = false;

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userName", user.getUserName());
//			map.put("company", user.getCompany());
			List<User> list = userDaoImpl.list(map, null, 0, 0);
			if(list.size() > 0) throw new Exception("用户名{" + user.getUserName() + "}已经存在，不允许重复");
			bool = userDaoImpl.save(user);
			bool = this.saveGroups(user, userGroupFlag, userDataperIdFlag, "save");
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
		return bool;
	}

	@Transactional(readOnly = false)
	public boolean update(User user, HashMap<Long, String> userGroupFlag, HashMap<Long, String> userDataperIdFlag) {
		boolean bool = false;
		//Set<Entry<Long, String>> entrys = userGroupFlag.entrySet();
		try {
			User userVO = userDaoImpl.findbyId(user.getUserId());
			//bool = userDaoImpl.update(user);
			userVO.setCompany(user.getCompany());
			userVO.setDepartment(user.getDepartment());
			userVO.setEmail(user.getEmail());
			userVO.setPassWordREQ(user.getPassWordREQ());
			userVO.setUpdateDate(user.getUpdateDate());
			userVO.setUpdateperson(user.getUpdateperson());
			userVO.setUserCName(user.getUserCName());
			userVO.setUserEName(user.getUserEName());
			userVO.setUserName(user.getUserName());
			userVO.setUserPassWord(user.getUserPassWord());
			userVO.setRemarks(user.getRemarks());
			bool = this.saveGroups(user, userGroupFlag, userDataperIdFlag, "update");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return bool;
	}

	public boolean saveGroups(User user, HashMap<Long, String> userGroupFlag,
			HashMap<Long, String> userDataperIdFlag, String flag) throws Exception {
		boolean bool = false;
			UserUserGroup group = new UserUserGroup();
			Set<Entry<Long, String>> entrys = userGroupFlag.entrySet();
			UserUserGroup bo = new UserUserGroup();
			for (Entry<Long, String> entry : entrys) {
				if (flag.equals("update")) {
					group = userUserGroupDaoImpl.findGroup(user.getUserId(),
							entry.getKey());
					bo = group;
				}
				UserGroup userGroup = new UserGroup();
				userGroup.setUserGroupId(entry.getKey());
				bo.setUser(user);
				bo.setUserGroup(userGroup);
				bo.setCreateperson(user.getCreateperson());
				bo.setCreateDate(user.getCreateDate());
				if ("1".equals(entry.getValue())) {
					bool = userUserGroupDaoImpl.save(bo);
				} else if ("2".equals(entry.getValue())) {
					bool = userUserGroupDaoImpl.remove(bo);
				} else {
					bool = true;
				}
			}
			
			UserDataper dataper = new UserDataper();
			Set<Entry<Long, String>> entryDatas = userDataperIdFlag.entrySet();
			UserDataper userDataper = new UserDataper();
			for (Entry<Long, String> entrydata : entryDatas) {
				if (flag.equals("update")) {
					dataper = userDataperDaoImpl.findGroup(user.getUserId(), entrydata.getKey());
					userDataper = dataper;
				}
				Dataper data = new Dataper();
				data.setCwtId(entrydata.getKey());
				userDataper.setUser(user);
				userDataper.setDataper(data);
//				userDataper.setCreatePerson(user.getCreateperson());
//				userDataper.setCreateDate(user.getCreateDate());
				if ("1".equals(entrydata.getValue())) {
					bool = userDataperDaoImpl.save(userDataper);
				} else if ("2".equals(entrydata.getValue())) {
					bool = userDataperDaoImpl.remove(userDataper);
				} else {
					bool = true;
				}
			}
		return bool;
	}

	public User getUserByName(String userName, String passWord)
			throws Exception {
		String pass = "";
		CipherUtil ci = new CipherUtil();
		if (passWord != null && !passWord.equals("")) {
			pass = ci.generatePassword(passWord);
		}
		return userDaoImpl.getUserByName(userName, pass);
	}

	@Override
	public List<Dataper> getUserDataper(Long userId) {
		List<Dataper> datapers = new ArrayList<Dataper>();
		User user = userDaoImpl.findbyId(userId);
		if(user == null) return datapers;
		Set<UserDataper> ud =user.getUserDataperSet();
		if(ud != null){
			for(UserDataper dvo : ud){
				datapers.add(dvo.getDataper());
			}
		}
		return datapers;
	}
	
	@Override
	public List<UserGroup> getUserGroups(Long userId,String type) {
		List<UserGroup> datapers = new ArrayList<UserGroup>();
		User user = userDaoImpl.findbyId(userId);
		if(user == null) return datapers;
		Set<UserUserGroup> ud =user.getUserUserGroup();
		if(ud != null){
			if(type == null){
				for(UserUserGroup dvo : ud){
					datapers.add(dvo.getUserGroup());
				}
			}else{
				for(UserUserGroup dvo : ud){
					UserGroup ug = dvo.getUserGroup();
					if(type.equals(ug.getGrouptype()))
						datapers.add(ug);
				}
			}
		}
		return datapers;
	}

	@Override
	public User findUserById(Long id) {
		User user = null;
		String queryString = "from User u where u.userId =("+ id + ") order by u.createDate";
		List<User> list = userDaoImpl.find(queryString);
		if (list != null && list.size() > 0) {
			user = list.get(0);
		}
		return user;
	}

	/**
	 * 查找用户名是否存在
	 * @param userName
	 * @param userId
	 * @return
	 */
	public boolean checkName(String userName, Long userId) {
		User user = null;
		String queryString = "from User u where u.userName =("+ userName + ") order by u.createDate";
		List<User> list = userDaoImpl.find(queryString);
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}
	/**
	 * 改变用户状态
	 * @param userIds
	 * @param status
	 * @return
	 */
	@Transactional(readOnly = false)
	public boolean changeStatus(List<Long> userIds, String status) {
		boolean bool = false;
		try {
			userDaoImpl.changeStatus(userIds, status);
			bool = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bool;
	}
	
	/**
	 * 有效员工
	 */
//	public List<User> searchValidUser(Map<String, Object> queryMap) {
//		StringBuilder queryString = new StringBuilder();
//		String field = " order by c.createDate desc";
//		queryString.append("from User as c ");
//		if (queryMap != null && queryMap.size() > 0) {
//			queryString.append(" where 1=1");
//			if (queryMap.get("companyIdList") != null
//					&& !"".equals(queryMap.get("companyIdList"))) {
//				queryString
//						.append(" and c.company.companyId in(:companyIdList)");
//			}
//			if (queryMap.get("userName") != null
//					&& !"".equals(queryMap.get("userName"))) {
//				queryString.append(" and c.userName like :userName");
//			}
//		}
//		queryString.append(field);
//
//		List<User> list = userDaoImpl.search(queryString.toString(), queryMap, null);
//		return list;
//	}
}
